
#include "GamePlayer.h"
#include "GameTeam.h"
#include "CreatureManager.h"
#include "msgDefine.h"


GameTeam::GameTeam()
{
	mMemberCount = 0;

	for ( fint32 i = 0 ; i < MAX_TEAM_CREATURE ; i++ )
	{
		mMembers[ i ] = F_NULL;
	}
}


GameTeam::~GameTeam()
{
	
}


fvoid			GameTeam::Init( GameCreature* leader )
{
	mMembers[ 0 ] = leader;
	mMemberCount++;

	leader->SetTeam( this );
}


fvoid			GameTeam::Release()
{
	gCreatureManager->RemoveTeam( this );

	for ( fint32 i = 0 ; i < mMemberCount ; ++i )
	{
		mMembers[i]->SetTeam( F_NULL );
	}

	for ( fint32 i = 0 ; i < mMemberCount ; i++ )
	{
		mMembers[ i ] = F_NULL;
	}

	mMemberCount = 0;
}


fbool			GameTeam::Join( GameCreature* c )
{
	if ( mMemberCount == MAX_TEAM_CREATURE )
	{
		return F_FALSE;
	}

	for ( fint32 i = 0 ; i < mMemberCount ; i++ )
	{
		if ( mMembers[ i ] == c )
		{
			return F_FALSE;
		}
	}

	mMembers[ mMemberCount ] = c; mMemberCount++;
	c->SetTeam( this );

	return F_TRUE;
}


fbool			GameTeam::Leave( GameCreature* c )
{
	c->SetTeam( F_NULL );

	if ( mMembers[ 0 ] == c )
	{
		Release();

		return F_TRUE;
	}

	for ( fint32 i = 1 ; i < mMemberCount ; i++ )
	{
		if ( mMembers[ i ] == c )
		{
			if ( mMemberCount == 2 )
			{
				Release();
				
			}
			else
			{
				mMembers[ i ] = F_NULL;
				for ( fint32 j = i ; j < mMemberCount - 1 ; j++ )
				{
					mMembers[ j ] = mMembers[ j + 1 ];
				}
			}

			return F_TRUE;
		}
	}

	return F_FALSE;
}


fbool			GameTeam::IsLeader( GameCreature* c )
{
	return mMembers[ 0 ] == c;
}


fvoid			GameTeam::UpdatePos()
{
	for ( fint32 i = 1 ; i < mMemberCount ; ++i )
	{
		mMembers[i]->GetMoveData().Pos = mMembers[0]->GetMoveData().Pos;
		mMembers[i]->GetMoveData().Direction = mMembers[0]->GetMoveData().Direction;
	}

}

